import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:输出二叉树的右视图
 * User: wangxin
 * Date: 2024-11-23
 * Time: 21:24
 */


   class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
      this.val = val;

  }

public class test1 {
    public static TreeNode reConstructBinaryTree(int[] preOrder, int[] vinOrder) {
        // write code here
        int n = preOrder.length;
        int m = vinOrder.length;
        if (m == 0 || n == 0) {
            return null;
        }
        TreeNode root = new TreeNode(preOrder[0]);
        for (int i = 0; i < m; i++) {
            if (root.val == vinOrder[i]) {
                root.left = reConstructBinaryTree(Arrays.copyOfRange(preOrder, 1, i + 1), Arrays.copyOfRange(vinOrder, 0, i));
                root.right = reConstructBinaryTree(Arrays.copyOfRange(preOrder, i + 1, n), Arrays.copyOfRange(vinOrder, i + 1, m));
                break;
            }

        }
        return root;
    }

    public static ArrayList<Integer> rightSideView(TreeNode root) {
        Map<Integer, Integer> mp = new HashMap<>();
        int maxDepth = -1;
        Stack<TreeNode> nodes = new Stack<>();
        Stack<Integer> depths = new Stack<>();
        nodes.push(root);
        depths.push(0);
        while (!nodes.isEmpty()) {
            TreeNode node = nodes.pop();
            int depth = depths.pop();

            if (node != null) {
                maxDepth = Math.max(maxDepth, depth);
                if (mp.get(depth) == null) {
                    mp.put(depth, node.val);
                }
                nodes.push(node.left);
                nodes.push(node.right);
                depths.push(depth + 1);
                depths.push(depth + 1);
            }
        }
        ArrayList<Integer> res = new ArrayList<>();
        for (int i = 0; i <= maxDepth; i++) {
            res.add(mp.get(i));
        }
        return res;
    }

    public static int[] solve(int[] preOrder, int[] vinOrder) {
        //空节点
        if (preOrder == null) {
            return new int[0];
        }
        TreeNode root = reConstructBinaryTree(preOrder, vinOrder);
        ArrayList<Integer> arrayList = rightSideView(root);
        int[] res = new int[arrayList.size()];
        for (int i = 0; i < res.length; i++) {
            res[i] = arrayList.get(i);
        }
        return res;
    }
}
   }
